// 多条件的搜索框封装
// 作者：wang
// 时间：2019-7-13
<template>
  <div class="tc-select-tags-search ly_flex ly_flex_just_between" :class="firstShow ? 'focus' : ''" @click="showSelete" v-click-outside="unShowSelect">
    <div class="tc-search-wrap ly_flex">
      <ul>
        <li>
          <!-- tag标签的内容 -->
          <div @click.stop="changeTagVal(tag)" class="tc-tags" v-if="tagList.length" v-for="(tag,index) in tagList" :key="index">
            <span v-if="tag.key">{{tag.key}}:</span><span> {{tag.value}}</span>
            <a @click.stop="deleteTag(tag.key,index)" v-if="firstShow" href="javascript:;" class="tc-tags-close-btn"><b>&times;</b></a>
          </div>
          <div class="tc-tags-space">
            <!-- tag标签转化为input输入框的内容 -->
            <span ref="_span" style="display: inline-block;white-space: pre;font-size: 12px;">{{value}}</span>
            <input v-model="inputVal" @keyup.enter="subNewObj(inputVal)" ref="_input" :autofocus="autofocus" type="text" style="width: 5px;max-width: 715px;display: none;"/>
            <pre ref="_pre" style="display: inline-block;position: absolute;top: -9999px;">{{inputVal}}</pre>
            <!-- 一级菜单的选择框 -->
            <div @click.stop="" v-show="dataShow && firstData && firstData.newData.length" class="first_select">
              <div class="title">{{firstData.title}}</div>
              <ul class="fir_sec">
                <li v-for="(item,index) in firstData.newData" :key="index" @click="changeKey(item)">{{item.name}}</li>
              </ul>
            </div>
             <!-- 二级菜单的多选框-->
            <div class="tc-tags-checkbox" v-if="checkShow">
              <el-checkbox-group class="ly_flex ly_flex_col" @change="getCheckVal" v-model="checkList">
                <el-checkbox v-for="(item,index) in firstObj.data" :key="index" :label="item">{{item.label}}</el-checkbox>
              </el-checkbox-group>
              <div class="tc-tag-footer ly_flex ly_flex_just_around">
                <a @click.stop="subNewObj(inputVal)"><el-button type="text">完成</el-button></a>
                <a @click.stop="subNewObj(null)"><el-button type="text">取消</el-button></a>
              </div>
            </div>
            <!-- 时间区间选择 -->
            <div class="tc-tags-checkbox" v-if="TimeShow">
              <el-date-picker
                v-model="inputVal"
                type="daterange"
                value-format="yyyy-MM-dd"
                @change="changeDate"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div> 
        </li>
      </ul>
      <div class="help-tips">
        <p class="text-weak">关键字用"|"分隔，过滤标签用回车键分隔</p>
      </div>
    </div>
    <!-- 搜索按钮-->
    <div class="tc-search-icon">
      <i class="el-icon-error" @click.stop="deleteTag(null,null,'delete')"></i>
      <i class="el-icon-search" @click.stop="submitAll"></i>
    </div>
  </div>
</template>

<script>
  export default {
    name: "inputDemo",
    props: ['dataObj'],
    data() {
      return {
        value: '',      //要搜索的键名
        inputVal: '',      //要搜索的值（input输入的值）
        firstShow: false,      //   input框的模拟聚焦效果
        dataShow: false,       //   第一个下拉框出现与否（选择要搜索的类别）
        autofocus:false,       //   input框自动聚焦
        checkShow:false,       //二级数据的多选框是否出现
        TimeShow:false,       //二级数据的多选框是否出现
        firstObj: {},        //储存当前选择的项
        checkList: [],       // 二级数据的多选框选择的列表
        firstData: {},      //父组件传给子组件的值
        endObj: {},    //最终给后端传的搜索条件
        tagList: [],    //tag标签中显示的值
      }
    },
    // 自定义组件（点击div外的）
    directives: {
      'click-outside': {
        // 指令的定义
        bind(el, binding, vnode) {
          function clickHandler(e) {
            // 这里判断点击的元素是否是本身，是本身，则返回
            if (el.contains(e.target)) {
              return false;
            }
            // 判断指令中是否绑定了函数
            if (binding.expression) {
              // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
              binding.value(e);
            }
          }
          // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
          el.__vueClickOutside__ = clickHandler;
          document.addEventListener('click', clickHandler);
        },
        update() {},
        unbind(el, binding) {
          // 解除事件监听
          document.removeEventListener('click', el.__vueClickOutside__);
          delete el.__vueClickOutside__;
        },
      }
    },
    created() {
    //  便利拿到数组，用新数组去做操作
      let arr = []
      this.firstData = this.dataObj
      this.firstData.data.length && this.firstData.data.forEach( (item,index) => {
        item['index'] = index
        arr.push({
          name: item.name,
          label: item.label,
          id: item.id,
          type: item.type,
          index: item.index,
          data: item.data
        })
      })
      this.firstData['newData'] = arr
    },
    watch: {
      inputVal(val) {
        setTimeout(() => {
          this.$refs._pre.clientWidth > 0 && this.spanWidth(this.$refs._pre.clientWidth)
        },100)
      },
    },
    methods: {
      //聚焦以后出现下拉框和聚焦效果
      showSelete() {
        if(this.firstObj && this.firstObj.type) {
          this.dataShow = false
          switch(this.firstObj.type) {
            case 'select':
              this.checkShow = true
              break;
            case 'dateTime':
              this.TimeShow = true
          }
        } else {
          this.dataShow = true
        }
        
        this.firstShow = true
        this.$refs._input.style.display = 'inline-block'
        this.$refs._span.style.display = 'inline-block'
        this.$nextTick( () =>{
          this.$refs._input.focus()
        } )
      },
      //input的长度根据文本的长度改变
      spanWidth(value) {
        this.$refs._input.style.width = (14 + value) + 'px'
      },
      //删除要选择的这个tag标签
      deleteTag(key,index,all=null) {
        // 清空tag标签的内容
        if(all) {
          this.tagList = []
          this.value = null;
          this.firstObj = {}
          this.inputVal = null;
          this.firstData.newData = Util.deepCopy(this.firstData.data)
          this.unShowSelect()
        } else {
          if(index !== null) {
            this.tagList.length && this.tagList.splice(index,1)
          }
          let arr = this.firstData.data
          arr.length && arr.forEach( (item,index) => {
            if(item.name==key) {
              this.firstData.newData.push(item)
            }
          })
          this.firstData.newData.sort(Util.compare('index'))
        }
        this.TimeShow = false;
        this.checkShow = false;
      },
      //点击除了聚焦地方的别的地方触发的事件
      unShowSelect() {
        setTimeout( () => {
          this.firstShow = false
          this.dataShow = false
          this.dataShow = false
          this.TimeShow = false;
          this.checkShow = false;
          this.$refs._input.style.display = 'none'
          this.$refs._span.style.display = 'none'
        },200)
      },
      //选择要发送的键值
      changeKey(val) {
        this.value = val.name + ':'
        this.firstObj = val
        this.dataShow = false
        this.firstShow = true
        switch(val.type) {
          case 'input':
            this.endObj[val.label] = null
            break;
          case 'select':
            this.checkShow = true
            this.endObj[val.label] = []
            break;
          case 'dateTime':
            this.TimeShow = true
            this.endObj[val.label] = null
        }
        this.firstData.newData.splice(this.firstData.newData.findIndex(i => i.id == val.id),1)
        this.$refs._input.style.display = 'inline-block'
        this.$nextTick( () =>{
          this.$refs._input.focus()
        })
      },
      //选择二级菜单下面的
      getCheckVal(val) {
        let arr = []
        let valArr = []
        val.length && val.forEach(item => {
          arr.push(item.label)
          valArr.push(item.value)
        })
        this.endObj[this.firstObj.label] = valArr
        let value = arr.join(' | ')
        this.inputVal = value
      },

      // 选择查询的时间区间
      changeDate(val) {
        // 具体的时间格式该怎么发送，到时候和后端具体商量
        this.$nextTick( () =>{
          this.$refs._input.focus()
        })
      },
      //点击tag标签修改要搜索的内容
      changeTagVal(tag) {
        // 如果input没有聚焦，就点击tag标签让tag标签聚焦
        if(!this.firstShow) {
          this.firstShow = true
          this.$refs._input.style.display = 'inline-block'
          this.$refs._span.style.display = 'inline-block'
          this.$nextTick( () =>{
            this.$refs._input.focus()
          } )
        } else {
          // 如果聚焦再点击的话就变成可修改的input
          // debugger
        }
      },
      //enter点击事件
      subNewObj(val) {
        // 判断是否有值传入
        if (val) {
          this.tagList.push({key: this.firstObj.name ? this.firstObj.name : '', value: val})
          if(!this.checkList.length) {
            this.endObj[this.firstObj.label] = val
          }
          this.value = null;
          this.inputVal = null;
          val = null;
          this.spanWidth(0)
        } else {
          // 判断是不是提交按钮
          if(this.firstObj.name) {
            this.deleteTag(this.firstObj.name,null)
            this.inputVal = null
            this.value = null
            this.unShowSelect()
          } else {
            // 是提交按钮就提交数据
            this.submitAll()
          }
        }
        this.checkShow = false
        this.TimeShow = false
        this.checkList = []
        this.firstObj = {}
      },
      // 整体提交所有的搜索条件
      submitAll() {
        // alert('正在查找。。。')
        this.subNewObj(this.inputVal)
        this.$emit('submitObj', this.endObj)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tc-select-tags-search {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 3px;
    box-shadow: 1px 1px 1px 1px #ddd;
    cursor: text;
    .tc-search-wrap {
      height: auto;
      position: relative;
      ul {
        white-space: nowrap;
        display: inline-block;
        vertical-align: middle;
        li {
          padding-left: 5px;
          position: relative;
          height: 20px;
          margin-top: 4px;
          display: inline-block;
          .first_select,.tc-tags-checkbox {
            position: absolute;
            display: flex;
            flex-direction: column;
            top: 30px;
            background: #ffffff;
            border: 1px solid #ebebeb;
            min-width: 180px;
            max-height: 240px;
            font-size: 12px;
            box-shadow: 1px 1px 1px 1px #e1e1e1;
            z-index: 999;
            .el-checkbox {
              margin: 0;
              width: 95%;
              padding-left: 5%;
              line-height: 25px;
              &:hover {
                background: rgb(242,242,242);
              }
            }
            .el-checkbox__input.is-checked+.el-checkbox__label {
              color: #000;
            }
            .tc-tag-footer {
              border-top: 1px solid #ddd;
              a {
                width: 100%;
                text-align: center;
                &:first-child {
                  border-right: 1px solid #ddd;
                }
                &:last-child {
                  .el-button--text {
                    color: #000;
                  }
                }

              }
            }
            .title {
              color: #bbb;
              line-height: 32px;
              padding: 0 10px;
              cursor: default;
            }
            .fir_sec {
              li {
                width: 100%;
                padding: 0 10px;
                line-height: 32px;
                cursor: pointer;
                &:hover {
                  background: rgb(242,242,242);
                }
              }
            }
          }
          .tc-tags {
            height: 20px;
            line-height: 18px;
            border: 1px solid #ddd;
            color: #000;
            font-size: 12px;
            background-color: #f2f2f2;
            margin-bottom: 2px;
            padding: 0 8px;
            float: left;
            cursor: pointer;
            box-sizing: border-box;
            max-width: 178px;
            text-overflow: ellipsis;
            overflow: hidden;
            margin-right: 5px;
            word-break: break-all;
            &:hover {
              background: #e5e5e5;
            }
          }
          .tc-tags-space {
            position: relative;
            display: inline-block;
            cursor: text;
            float: left;
            input {
              border: none;
              outline: 0;
              padding: 0 0 0 2px;
              margin: 0;
              height: 20px;
              font-size: 12px;
            }
          }
        }
      }
    }
    .help-tips {
      position: relative;
      font-size: 12px;
      text-align: left;
      display: inline-block;
      line-height: 28px;
      overflow: hidden;
      vertical-align: top;
      height: 28px;
      .text-weak {
        color: #bbb;
        padding-left: 10px;
        line-height: 30px ;
      }
    }
    .tc-search-icon {
      i {
        font-weight: 900;
        line-height: 30px;
        float: left;
        padding: 0 4px;
        font-size: 14px;
        color: rgb(136, 136, 136);
        cursor: pointer;
        &:hover {
          color: rgb(68,68,68);
        }
      }
    }

  }
  .focus {
    .tc-search-wrap>ul {
      margin-bottom: 2px;
      li {
        float: left;
        height: auto;
        .tc-tags {
          max-width: initial;
          white-space: initial;
          overflow: initial;
          height: auto;
          margin-right: 5px;
          position: relative;
          padding-right: 26px;
          .tc-tags-close-btn {
            position: absolute;
            z-index: 99;
            right: 5px;
            bottom: 2px;
            line-height: 16px;
            height: 16px;
            font-size: 16px;
            display: block;
          }
        }
        div {
          float: left;
        }
      }
    }
    .help-tips {
      display: none;
    }
    .tc-search-icon {
      display: flex;
    }
  }
</style>
